using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using TinyERP.Framework;
using TinyERP.Framework.Controls;
using Bamboo.Core.Data;
using Bamboo.Core.Common.Collection;


using TinyERP.Core.Business;
using TinyERP.Core.DTO;
using TinyERP.Core.View.Controls;
using log4net;

namespace TinyERP.Core.View
{
    public class UserListForm : BaseListForm
    {
		private DataGridViewTextBoxColumn userNameColumn;
		private DataGridViewTextBoxColumn fullNameColumn;
		private DataGridViewTextBoxColumn addressColumn;
		private DataGridViewTextBoxColumn phoneColumn;
		private DataGridViewTextBoxColumn birthdateColumn;
		private DataGridViewTextBoxColumn emailColumn;
		
		private DataGridViewTextBoxColumn userGroupColumn;
		private DataGridViewTextBoxColumn departmentColumn;
        private ILog logger = LogManager.GetLogger(typeof(UserListForm));
		public IUserService UserService 
		{
			get
			{
				return (IUserService) ServiceLocator.GetService("UserServiceProxy");
			}
		}
		

        /// <summary> 
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary> 
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Component Designer generated code

        /// <summary> 
        /// Required method for Designer support - do not modify 
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.userNameColumn = new System.Windows.Forms.DataGridViewTextBoxColumn();
            this.fullNameColumn = new System.Windows.Forms.DataGridViewTextBoxColumn();
            this.addressColumn = new System.Windows.Forms.DataGridViewTextBoxColumn();
            this.phoneColumn = new System.Windows.Forms.DataGridViewTextBoxColumn();
            this.birthdateColumn = new System.Windows.Forms.DataGridViewTextBoxColumn();
            this.emailColumn = new System.Windows.Forms.DataGridViewTextBoxColumn();
            this.userGroupColumn = new System.Windows.Forms.DataGridViewTextBoxColumn();
            this.departmentColumn = new System.Windows.Forms.DataGridViewTextBoxColumn();
            this.bottomPanel.SuspendLayout();
            this.contentPanel.SuspendLayout();
            this.navigationPanel.SuspendLayout();
            this.SuspendLayout();
            // 
            // searchPanel
            // 
            this.searchPanel.Size = new System.Drawing.Size(631, 31);
            // 
            // bottomPanel
            // 
            this.bottomPanel.Location = new System.Drawing.Point(0, 31);
            this.bottomPanel.Size = new System.Drawing.Size(631, 303);
            // 
            // controlPanel
            // 
            this.controlPanel.Location = new System.Drawing.Point(0, 267);
            this.controlPanel.Size = new System.Drawing.Size(631, 36);
            // 
            // contentPanel
            // 
            this.contentPanel.Size = new System.Drawing.Size(631, 267);
            // 
            // navigationPanel
            // 
            this.navigationPanel.Location = new System.Drawing.Point(0, 237);
            this.navigationPanel.Size = new System.Drawing.Size(631, 30);
            // 
            // paging
            // 
            this.paging.Size = new System.Drawing.Size(631, 30);
            // 
            // userNameColumn
            // 
            this.userNameColumn.Name = "userNameColumn";
           
            // 
            // fullNameColumn
            // 
            this.fullNameColumn.Name = "fullNameColumn";
            // 
            // addressColumn
            // 
            this.addressColumn.Name = "addressColumn";
            // 
            // phoneColumn
            // 
            this.phoneColumn.Name = "phoneColumn";
            // 
            // birthdateColumn
            // 
            this.birthdateColumn.Name = "birthdateColumn";
            // 
            // emailColumn
            // 
            this.emailColumn.Name = "emailColumn";
            // 
            // userGroupColumn
            // 
            this.userGroupColumn.Name = "userGroupColumn";
            // 
            // departmentColumn
            // 
            this.departmentColumn.Name = "departmentColumn";
            // 
            // UserListForm
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.Name = "UserListForm";
            this.bottomPanel.ResumeLayout(false);
            this.contentPanel.ResumeLayout(false);
            this.navigationPanel.ResumeLayout(false);
            this.navigationPanel.PerformLayout();
            this.ResumeLayout(false);

        }

        #endregion


        protected override void BuildDefaultSearchConditions()
        {
            searchConditions = new List<SearchCondition>();
            SearchCondition condition = new SearchCondition();
            condition.SearchField = "UserName";
            condition.SearchParameterName = "Name";
            condition.SearchOperator = SearchOperator.LIKE;
            string defaultSearchFieldValue = searchBar.SearchValue;
            condition.SearchParameterValue = "%" + defaultSearchFieldValue + "%";
            searchConditions.Add(condition);
        }

        private void SetupDataGridView()
        {
this.dataGridView.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
			this.userNameColumn
			,
			this.fullNameColumn
			,
			this.addressColumn
			,
			this.phoneColumn
			,
			this.birthdateColumn
			,
			this.emailColumn
			,
			
			this.userGroupColumn
			,
			this.departmentColumn
            });
            
			this.userNameColumn.DataPropertyName = "UserName";
			this.userNameColumn.HeaderText = ModuleResourceManager.GetInstance().GetStringFromModuleResourceKey("UserName, TinyERP.Core");
			this.userNameColumn.Name = "userNameColumn";
			this.userNameColumn.Tag = "userName";
			this.userNameColumn.ReadOnly = true;
			this.userNameColumn.SortMode = DataGridViewColumnSortMode.Programmatic;
			this.fullNameColumn.DataPropertyName = "FullName";
			this.fullNameColumn.HeaderText = ModuleResourceManager.GetInstance().GetStringFromModuleResourceKey("FullName, TinyERP.Core");
			this.fullNameColumn.Name = "fullNameColumn";
			this.fullNameColumn.Tag = "fullName";
			this.fullNameColumn.ReadOnly = true;
			this.fullNameColumn.SortMode = DataGridViewColumnSortMode.Programmatic;
			this.addressColumn.DataPropertyName = "Address";
			this.addressColumn.HeaderText = ModuleResourceManager.GetInstance().GetStringFromModuleResourceKey("Address, TinyERP.Core");
			this.addressColumn.Name = "addressColumn";
			this.addressColumn.Tag = "address";
			this.addressColumn.ReadOnly = true;
			this.addressColumn.SortMode = DataGridViewColumnSortMode.Programmatic;
			this.phoneColumn.DataPropertyName = "Phone";
			this.phoneColumn.HeaderText = ModuleResourceManager.GetInstance().GetStringFromModuleResourceKey("Phone, TinyERP.Core");
			this.phoneColumn.Name = "phoneColumn";
			this.phoneColumn.Tag = "phone";
			this.phoneColumn.ReadOnly = true;
			this.phoneColumn.SortMode = DataGridViewColumnSortMode.Programmatic;
			this.birthdateColumn.DataPropertyName = "Birthdate";
			this.birthdateColumn.HeaderText = ModuleResourceManager.GetInstance().GetStringFromModuleResourceKey("Birthdate, TinyERP.Core");
			this.birthdateColumn.Name = "birthdateColumn";
			this.birthdateColumn.Tag = "birthdate";
			this.birthdateColumn.ReadOnly = true;
			this.birthdateColumn.SortMode = DataGridViewColumnSortMode.Programmatic;
			this.emailColumn.DataPropertyName = "Email";
			this.emailColumn.HeaderText = ModuleResourceManager.GetInstance().GetStringFromModuleResourceKey("Email, TinyERP.Core");
			this.emailColumn.Name = "emailColumn";
			this.emailColumn.Tag = "email";
			this.emailColumn.ReadOnly = true;
			this.emailColumn.SortMode = DataGridViewColumnSortMode.Programmatic;
			
			this.userGroupColumn.DataPropertyName = "UserGroupName";
			this.userGroupColumn.HeaderText = ModuleResourceManager.GetInstance().GetStringFromModuleResourceKey("UserGroup, TinyERP.Core");
			this.userGroupColumn.Name = "userGroupColumn";
			this.userGroupColumn.Tag = "userGroup";
			this.userGroupColumn.ReadOnly = true;
			this.userGroupColumn.SortMode = DataGridViewColumnSortMode.NotSortable;
			this.departmentColumn.DataPropertyName = "DepartmentName";
			this.departmentColumn.HeaderText = ModuleResourceManager.GetInstance().GetStringFromModuleResourceKey("Department, TinyERP.Core");
			this.departmentColumn.Name = "departmentColumn";
			this.departmentColumn.Tag = "department";
			this.departmentColumn.ReadOnly = true;
			this.departmentColumn.SortMode = DataGridViewColumnSortMode.NotSortable;

            this.dataGridView.AutoGenerateColumns = false;
            this.dataGridView.MultiSelect = false;
            this.dataGridView.ModuleAssemblyName = "TinyERP.Core";
            this.dataGridView.AllowUserToOrderColumns = true;
            this.dataGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
            InitializeSortKeyMap();
        }
        
        private void InitializeSortKeyMap() 
        {
			this.dataGridView.SortKeyMap["UserGroupName"] = "UserGroup.Name";
			this.dataGridView.SortKeyMap["DepartmentName"] = "Department.Name";
        }

		public UserListForm() : base()
        {
            InitializeComponent();
			SetupDataGridView();
        }
        

		public override void OnNew()
        {
            UserEditInfoForm editForm = new UserEditInfoForm();
            editForm.OnNeedReloadData += delegate(object senderObj)
            {
                LoadGridData();
            };
            new DialogHelper(editForm).ShowDialog(UIManager.MainScreen);
        }
        

		public override void OnDelete()
        {
			if (this.dataGridView.SelectedRows.Count == 0)
            {
                return;
            }
            UserDTO user = (UserDTO)this.dataGridView.SelectedRows[0].DataBoundItem;
            try 
			{
                if (MessageBox.Show(CommonMessage.GetDeleteConfirmMessage("User"),
                CommonMessage.GetConfirmationText(), MessageBoxButtons.OKCancel) == DialogResult.OK)
                {
					UserService.DeleteUserByID(user.ID);
					MessageBox.Show(CommonMessage.GetDeleteSuccessMessage("User"));
					LoadGridData();
				}
			}
			catch(Exception ex) 
			{
				logger.Error(ex);
				MessageBox.Show(CommonMessage.GetCanNotDeleteError("User"));
			}
        }
        
        
        public override void OnEdit()
        {
            if (this.dataGridView.SelectedRows == null || this.dataGridView.SelectedRows.Count == 0)
            {
                return;
            }
            UserDTO userDTO = (UserDTO) this.dataGridView.SelectedRows[0].DataBoundItem;
            UserEditInfoForm editForm = new UserEditInfoForm();
            editForm.IsEditMode = true;
            editForm.ApplyACL(this.AllowEdit, this.AllowDelete, this.AllowCreate);
            editForm.User = userDTO;
			editForm.OnNeedReloadData += delegate(object senderObj)
            {
                LoadGridData();
            };
            new DialogHelper(editForm).ShowDialog(UIManager.MainScreen);
        }
        

        

        
		protected override void LoadGridViewSearchData(IList<SearchCondition> searchConditions, Bamboo.Core.Data.SortDirection sortDirection, string columnName)
        {
			long totalRecord = 0;
            IList userList = UserService.SearchUser(paging.CurrentPage, paging.PageSize, searchConditions, columnName, sortDirection, out totalRecord);
            this.paging.TotalRecord = totalRecord;
            if (userList.Count == 0)
            {
                MessageBoxHelper.ShowInformation(AppResourceManager.GetInstance().GetString("ResultNotFound"));
            }
            SortableBindingList<UserDTO> sortableUserList = SortableBindingList<UserDTO>.CreateSortableBindingList(userList);
            this.dataGridView.DataSource = sortableUserList;
        }

        protected override void LoadGridViewDefaultData(Bamboo.Core.Data.SortDirection sortDirection, string columnName) 
        {
        	long totalRecord = 0;
            IList userList = UserService.GetAllUser(paging.CurrentPage, paging.PageSize, columnName, sortDirection, out totalRecord);
            this.paging.TotalRecord = totalRecord;
            SortableBindingList<UserDTO> sortableUserList = SortableBindingList<UserDTO>.CreateSortableBindingList(userList);
            this.dataGridView.DataSource = sortableUserList;
        }

             

    }
}
